<?php

namespace ApplicationsModule\GalleryModule;

use Nette\Image;
use Nette\Application\AppForm;
use Nette\Forms\Form;
use Nette\Web\HttpUploadedFile;
use Nette\Environment;

use WebtopModule\BasePresenter;

use ApplicationsModule\GalleryModule\Gallery;
use ApplicationsModule\GalleryModule\PicasaTokenNotReachableException;
use ApplicationsModule\GalleryModule\PicasaTokenNotValidException;
/**
 * Description of DefaultPresenter
 *
 * @author Honza
 */
class DefaultPresenter extends BasePresenter {
    
    
    private $galleryModel;
    const REST_LOAD = '../api/rest/load?out=image&what=';
    const CALLBACK_URI = 'http://localhost/AlbireoIS/document_root/kernel/picasa/test';


    public function startup() {
	parent::startup();
	header ( "Content-type:text/html; charset=utf-8" ); // TODO: poresit
        if ($this->isAjax()) {
	    $this->invalidateControl("celebriogalleryappSnippet");
	}
	if(!$this->getUser()->isLoggedIn()) {
            throw new \Exception("User is not authenticated");
	    return;
        }
    }
    
    public function actionDefault() {
        //$this->redirect('PicasaAuthenticator:Default');
    }
    
    public function renderDefault($url) {
        //$args = array("picasa_token" => $this->getSession("picasa")->token);
        //$model = $this->getGalleryModel($args);
        $services = $this->checkAvailableServices();
        $model = $this->getGalleryModel();
        //TODO odmazat nasledujici radek
        $samples = array();
        $samples = $model->getSamples($services);
            //Depracate
//            if(empty($samples)) {
//                $this->createDefault();
//                $samples = $model->getSamples();
//            }
        
        /*foreach($samples as $sample) {
            $sample->setPictureUrl(self::REST_LOAD . $sample->getPictureUrl());
        }*/
            $this->template->samples = $samples;
        
        /*$gallery = new Gallery();
        $samples = $gallery->getGalleries();
        
        $samplesUrl = array();
        foreach($samples as $sample) {
            $galleryUrl = $sample->getUrl() . $sample->getName();
            $photosAsDF = $gallery->getPhotos($galleryUrl)->getData();
            $samplesUrl[$galleryUrl] = $this->getArrayFromDF($photosAsDF);
        }
        
        $this->template->samplesUrl = $samplesUrl;*/

    }
    
    public function renderSavePage() {
        $this->template->saveGalleryForm = $this['saveGalleryForm'];
        $this->template->savePhotoForm = $this['savePhotoForm'];
    }
    
    protected function createComponentSaveGalleryForm() {
        $form = new appForm();
        //$form->addText("to", ("To:"))->addRule(Form::FILLED, _("Please provide name of new gallery"));
        $form->addText("name",_("Name:"))
	     ->addRule(Form::FILLED, _('Please provide name of your new gallery.'));
        $services = $this->checkAvailableServices();
        $servNames = array();
        foreach($services as $service) {
            $servNames[$service::NAME] = $service::NAME;
        }
        $form->addSelect("service", _("Service:"), $servNames);
        $form->addSubmit("submitted", _("Send"));
        $form->onSubmit[] = callback($this, 'saveGalleryFormSubmitted');
        return $form;
    }
    
    function saveGalleryFormSubmitted($form) {
        $service = $form->values["service"];
        $name = $form->values["name"];
        $model = $this->getGalleryModel();
        $model->makeGallery($service, $name);
	if ($this->isAjax()) $this->invalidateControl("saveGalleryForm");
    }
    
    protected function createComponentSavePhotoForm() {
        $form = new appForm();
//        $form->addCheckbox('newGallery',_('Add to new gallery?'));
//        $form->addText('newGalleryName',_('Name of new gallery:'));
        
        $gallery = $this->getGalleryModel();
        $names = $gallery->getGalleryNames($this->checkAvailableServices());
        $form->addSelect('galleryInfo',_('Gallery:'), $names);
                
        /*$galleryNames = $this->getGalleryNames();
        if(!empty($galleryNames)) {
            $form->addSelect('galleryName',_('Gallery:'), $galleryNames);
        } else {
            $this->createDefault();
            $form->addSelect('gallery', 
                    ('Gallery:'), 
                    $this->getGalleryNames());
        }*/
        $form->addFile("file1",_("Picture 1:"));
        $form->addFile("file2",_("Picture 2:"));
        $form->addFile("file3",_("Picture 3:"));
        $form->addFile("file4",_("Picture 4:"));
        $form->addFile("file5",_("Picture 5:"));
        
        //$form->addSubmit('addNext',_('Add next file'));
        
        $form->addSubmit('submitted',_('Send'));
        $form->onSubmit[] = callback($this, 'savePhotoFormSubmitted');
        return $form;
    }
    
    //TODO: ZDE ZAJISTIT, ABY MAKE GALLERY OPRAVDU FUNGOVALO
    function savePhotoFormSubmitted($form) {
        $values = $form->values;
        $model = $this->getGalleryModel();  
        $userID = $this->getUser()->getIdentity()->id;
//        if(!empty($values["newGalleryName"])) {
//            $galleryToSave = $values["newGalleryName"];
//            $model->makeGallery($galleryToSave);
//        } else {
//            $galleryToSave = $values["galleryInfo"];
//        }
        $info = $this->parseGalleryInfo($values["galleryInfo"]);
        $model->setService($info["service"]);
        $toSave = array();
        foreach($values as $value) {
            if(!($value instanceof HttpUploadedFile)) continue;
            if($value->getName() == "")   continue;
            
            //TODO: check if file is image should be javascript on client side!
            if(($value->isImage())) {
                $image = $value->getImage()->toString();
                $mimetype = $value->getContentType();
                $model->savePhoto($info["galleryName"], $value->getName(), $image, $mimetype);
            } else {
                $this->template->photoErr = _("Error occured. Have you uploaded image(s)?");
                break;
            }
        }
        
	if ($this->isAjax()) $this->invalidateControl("savePhotoForm");
    }
    
    private function parseGalleryInfo($galleryInfo) {
        $arg = explode(",", $galleryInfo);
        return array("galleryName" => $arg[0], "service" => $arg[1]);
    }
    
    
    /**
     * DEPRACATED
     * 
     * @param type $url 
     */
    public function renderSample($url) {
        $gallery = new Gallery();
        $sample = $gallery->getSample($url);
        $image = Image::fromString($sample->getData());
        
        $image->resize(null, 300);
        
        $image->send();
                
        //\fpassthru($handle)
        
    }
    
    public function renderImage($galleryID, $userID, $serviceName) {
        $this->template->images = array();
        $model = $this->getGalleryModel();
        $photos = $model->getPhotos($galleryID, $userID, $serviceName);
        $result = array();
 
        $this->template->images = $photos;
    }
    
    private function getGalleryModel($args = null) {
        if($this->galleryModel == null) {
            $this->galleryModel = new Gallery($this->getUser(), $args);
        }
        return $this->galleryModel;
    }
    
    private function checkAvailableServices() {
        $model = $this->getGalleryModel();
        try {
            $services = $model->getAvailableServices();
        } catch(PicasaTokenNotReachableException $e) {
            $this->redirect("PicasaAuthenticator:Default");
        }
        return $services;
    }
}